<template>
  <div class="real-time-div">
    <div v-if="pageSwitchBool" style="height:100%">
      <div :id="mapDiv"></div>
      <!-- 视频弹框 -->
      <div
        style="width: 600px;
        height:100%;
        position: absolute;
        z-index: 99999;
        left: 4rem;
        top: 1.2rem;
        border: 0;"
        v-if="videoBool"
      >
        <a
          class="btn-close maintenance-removeSolid"
          href="javascript:;"
          @click="closeVideo()"
        ></a>
        <video
          id="myPlayer"
          :src="playerUrl"
          poster=""
          controls
          playsInline
          webkit-playsinline
          autoplay
          style="width: 600px;height: 400px;"
        ></video>
      </div>
      <!-- 火警列表 -->
      <div class="gg-fire-content">
        <div class="gg-fire-icon" @click="fireClick()"></div>
        <div class="fire-alarm-outside">
          <div id="monitor-alarm-list" class="gg-fire-panel scroll-normal">
            <dl
              v-for="(item, index) in alarmList"
              :key="index"
              :class="['clearfix', 'gg-fire-dl', index == alarmList.length - 1 ? '' : 'gg-fire-bd']"
              @click="openFloorPage(item.buildId,item.floorId,item.deviceId)"
            >
              <div class="fire-alarm-time">
                <div class="gg-fire-dt">{{ item.warningTimeHH }}</div>
                <div class="gg-fire-date">{{ item.warningTimeDD }}</div>
              </div>
              <div class="gg-fire-dd">
                <h3 class="gg-fire-title" :title="item.deviceType">
                  {{ item.deviceType }}
                </h3>
                <p class="gg-fire-add" :title="item.deviceAddress">
                  {{ item.deviceAddress }}
                </p>
              </div>
            </dl>
            <div v-if="alarmList.length == 0" class="gg-text-notice">
              暂无报警！
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-else>
      <FloorStoreyInfo :regionList="buildArr" :region="region" :currentFloorParent="currentFloor" :currentDeviceParent="currentDevice" :rowData="rowData" @goBack="goBack"></FloorStoreyInfo>
    </div>
  </div>
</template>
<script>
import api from "~/config/http";
import mapConfig from "~/config/mapConfig";
import { Message, MessageBox } from "element-ui";
import FloorStoreyInfo from "./FloorStoreyInfo";
export default {
  components: {
    FloorStoreyInfo
  },
  props: {
    rowData: {
      type: Object
    }
  },
  data() {
    return {
      pageSwitchBool:true,//展示那个页面
      orgId: "",
      mapDiv: "g2map",
      g2map: {}, //地图对象
      elementLayer: {}, //元素图层
      tooltipWare: {},
      aerialviewImg: "", //楼层平面图地址
      videoBool: false, //是否展示视频
      playerUrl: "", //播放视频地址
      alarmList: [], //报警列表
      buildArr:[],//楼栋楼层数据
      region:"",//楼栋楼层值
      currentFloor:"",//当前楼层
      currentDevice:""//当前设备
    };
  },
  methods: {
    //设备信息点击了返回按钮
    goBack(){
      this.pageSwitchBool=true;
      const _this = this;
      this.$nextTick(function(){
        _this.initPage();
      })
    },
    //初始化页面
    initPage() {
      //初始化地图
      const _this = this;
      this.initMap().then(() => {
        //初始化楼层平面图
        let floorUrl =
          api.forent_url.maintenance_service_url +
          "/recordEnterprise/enterprises/1/" +
          _this.rowData.unitId;
        api.get(floorUrl).then(res => {
          if (res && res["code"] == "success") {
            let data = res["data"][0] || "";
            if (data && data.aerialviewImg) {
              //楼层平面图地址
              _this.aerialviewImg =
                api.forent_url.image_url + "/floorImage/" + data.aerialviewImg;
              //初始化楼层平面图
              _this.initFloorImg(_this.aerialviewImg);
              //获取监测建筑信息并加载
              _this.queryMonitoringBuildingInformation();
              //获取企业报警列表
              _this.getAlarmList();
            } else {
              Message.error("暂无楼层图！");
            }
          } else {
            Message.error("暂无楼层图！");
          }
        });
      });
    },
    //初始化地图
    initMap() {
      const _this = this;
      return new Promise((resolve, reject) => {
        this.g2map = new _this.gs2.carto.Map({
          defaultExtent: mapConfig.defaultExtent3857
        });
        this.g2map.init({
          targetId: this.mapDiv
        });
        this.elementLayer = new _this.gs2.lys.ElementLayer();
        this.elementLayer.setZIndex(9);
        this.g2map.addLayer(this.elementLayer);
        this.tooltipWare = new _this.gs2.ext.TooltipWare({
          excluseLayerIds: this.elementLayer.getLayerId(),
          map: this.g2map
        });
        resolve();
      });
    },
    //初始化楼层平面图页面
    initFloorImg(imgUrl) {
      let _this = this;
      let img = new Image();
      img.src = imgUrl;
      img.onload = function() {
        let w = img.width * 1000;
        let h = img.height * 1000;
        let imagLayer = new _this.gs2.lys.ImageLayer({
          imageType: 702,
          extent: [0, 0, w, h], //图片范围，请按照坐标系的范围给出，此为3857的坐标系范围
          crossOrigin: "anonymous", //跨域
          url: imgUrl // 图层服务 url
        });
        _this.g2map.addLayer(imagLayer);
        let point = new _this.gs2.geom.Point({
          x: w / 2,
          y: h / 2 - 40000,
          spatialReference: _this.gs2.geom.SpatialReference.EPSG3857
        });
        _this.g2map.setCenter(point);
        _this.g2map.zoomTo(8);
      };
    },
    //获取监测建筑信息并加载
    queryMonitoringBuildingInformation() {
      let serviceUrl =
        api.forent_url.maintenance_service_url + "/recordEnterprise/getTAndAByUnitId";
      api.post(serviceUrl, { unitId: this.rowData.unitId ,orgId:this.orgId,type:"2"}).then(res => {
        if (res && res["code"] == "success") {
          let buildArr = res["data"] || [];
          this.buildArr = buildArr;
          if (buildArr && buildArr.length > 0) {
            for (let key in buildArr) {
              let build = buildArr[key];
              if (build["unitPointX"] !== "" && build["unitPointY"] !== "") {
                let point = new this.gs2.geom.Point({
                  x: build["unitPointX"],
                  y: build["unitPointY"],
                  spatialReference: this.gs2.geom.SpatialReference.EPSG3857
                });
                let pictureMarker = new this.gs2.syms.Picturemarkersymbol({
                  source:
                    "",
                  width: 40,
                  height: 40,
                  offsetX: 20,
                  offsetY: 20
                });
                let ele = new this.gs2.ele.Element({
                  geometry: point,
                  symbol: pictureMarker
                });
                ele.tag = build;
                this.elementLayer.add(ele);
                //设备数  展示 总设备数
                if (build.runState === NaN || build.runState === "") {
                  build.runState = 0;
                }
                if (build.alarmState === NaN || build.alarmState === "") {
                  build.alarmState = 0;
                }
                if (build.troubleType === NaN || build.troubleType === "") {
                  build.troubleType = 0;
                }
                if (build.warningState === NaN || build.warningState === "") {
                  build.warningState = 0;
                }
                let build_monitor = 'style="display:block"';
                let simple_monitor = 'style="display:none"';
                let build_offset = 'style="top:5px"';
                let simple_state = "";
                if (build.alarmState > 0) {
                  simple_state = '<div class="simple-state-alarm"></div>';
                } else {
                  if (build.warningState > 0) {
                    simple_state = '<div class="simple-state-warn"></div>';
                  } else {
                    if (build.troubleType > 0) {
                      simple_state = '<div class="simple-state-trouble"></div>';
                    } else {
                      simple_state = '<div class="simple-state-normal"></div>';
                      build_monitor = 'style="display:none"';
                      simple_monitor = 'style="display:block"';
                      build_offset = 'style="top:139px"';
                    }
                  }
                }
                let tooltipTemplate =
                  '<div class="gg-build-monitor" ' +
                  build_offset +
                  ">" +
                  '                    <div class="gg-build-head"' +
                  build_monitor +
                  '><div class="build-head-name" title="' +
                  build.buildName +
                  '">' +
                  build.buildName +
                  '</div><span class="maintenance-arrowBottom"></span></div>\n' +
                  '                    <div class="gg-build-body" ' +
                  build_monitor +
                  ">" +
                  '                      <div class="total_stateNum"><span class="build_state_title">设备数</span><span class="build_state_num">' +
                  build.allCount +
                  "</span></div> " +
                  '                      <div class="build_stateNum build_state_alarm"><span class="build_state_title">火警</span><span class="build_state_num" style="color: #f03718">' +
                  build.alarmState +
                  "</span></div> " +
                  '                      <div class="build_stateNum build_state_warn"><span class="build_state_title">电气火灾预警</span><span class="build_state_num" style="color: #5c52cc">' +
                  build.warningState +
                  "</span></div> " +
                  '                      <div class="build_stateNum build_state_trouble"><span class="build_state_title">消防设施故障</span><span class="build_state_num" style="color: #ff7800">' +
                  build.troubleType +
                  "</span></div> " +
                  '                      <div class="build_stateNum build_state_abnormal"><span class="build_state_title">监测设备异常</span><span class="build_state_num" style="color: #a1a8b2">' +
                  build.abnormalState +
                  "</span></div> " +
                  "                    </div>" +
                  ' <div class="gg-build-simple"' +
                  simple_monitor +
                  ">" +
                  simple_state +
                  '<span class="simple-head-name">' +
                  build.buildName +
                  '</span><span class="maintenance-arrowTop"></span></div>' +
                  "                  </div>";

                var tooltip = new this.gs2.ext.Tooltip({
                  anchor: point, //提示在地图上停靠位置
                  content: tooltipTemplate, //提示内容
                  layerId: this.elementLayer.getLayerId(), //提示所在图层ID
                  offset: [-94, -210], //位置偏移量
                  className: "g2-tooltip" //tooltip样式
                });
                this.tooltipWare.add(tooltip);
                //加载视频点信息
              }
            }
          }
          this.loadVideoBuild();
        } else {
          this.loadVideoBuild();
          Message.error("获取监测建筑信息失败!");
        }
      });
    },
    //加载视频点信息
    loadVideoBuild() {
      let serviceUrl =
        api.forent_url.maintenance_service_url + "/recordEnterprise/getVideoInfoList";
      api.post(serviceUrl, { unitId: this.rowData.unitId,orgId:this.orgId}).then(res => {
        if (res && res["code"] == "success") {
          let data = res["data"] || [];
          if (data && data.length > 0) {
            let elements = [];
            for (let i in data) {
              let point = new this.gs2.geom.Point({
                x: data[i].longitude,
                y: data[i].latitude,
                spatialReference: this.gs2.geom.SpatialReference.EPSG3857
              });
              let pictureMarker = new this.gs2.syms.Picturemarkersymbol({
                source:
                  "",
                width: 40,
                height: 40,
                offsetX: 20,
                offsetY: 20
              });
              let ele = new this.gs2.ele.Element({
                geometry: point,
                symbol: pictureMarker
              });
              ele.tag = data[i];
              ele.type = "video";
              elements.push(ele);
            }
            this.elementLayer.addElements(elements);
          }
          //绑定事件
          this.initEvent();
        } else {
          Message.error("查询视频点信息失败!");
        }
      });
    },
    //获取企业报警列表
    getAlarmList() {
      let serviceUrl =
        api.forent_url.maintenance_service_url + "/recordEnterprise/getLyMonitorListInfo";
      api
        .get(serviceUrl, { unitId: this.rowData.unitId, runState: 1 ,orgCode:this.orgId})
        .then(res => {
          if (res && res["code"] == "success") {
            let data = res["data"] || [];
            let fire_icon = $(".gg-fire-icon");
            if (data && data.length > 0) {
              Date.prototype.format = function(fmt) {
                var o = {
                  "M+": this.getMonth() + 1, //月份
                  "d+": this.getDate(), //日
                  "h+": this.getHours(), //小时
                  "m+": this.getMinutes(), //分
                  "s+": this.getSeconds(), //秒
                  "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                  S: this.getMilliseconds() //毫秒
                };
                if (/(y+)/.test(fmt)) {
                  fmt = fmt.replace(
                    RegExp.$1,
                    (this.getFullYear() + "").substr(4 - RegExp.$1.length)
                  );
                }
                for (var k in o) {
                  if (new RegExp("(" + k + ")").test(fmt)) {
                    fmt = fmt.replace(
                      RegExp.$1,
                      RegExp.$1.length == 1
                        ? o[k]
                        : ("00" + o[k]).substr(("" + o[k]).length)
                    );
                  }
                }
                return fmt;
              };
              fire_icon.removeClass("gg-fire-icon_default");
              fire_icon.addClass("gg-fire-icon_fire");
              for (let i in data) {
                let alarm = data[i];
                let warningTime = new Date(alarm.warningTime);
                data[i].warningTimeHH = warningTime.format("hh:mm");
                data[i].warningTimeDD = warningTime.format("yyyy-MM-dd");
              }
            } else {
              fire_icon.removeClass("gg-fire-icon_fire");
              fire_icon.addClass("gg-fire-icon_default");
            }
            this.alarmList = data;
          } else {
            Message.error("获取企业报警列表失败！");
          }
        });
    },
    //绑定事件
    initEvent() {
      //地图点击事件
      this.mapClick();
      //地图划入事件
      this.mapMousemove();
      //展开
      $(".gg-build-simple .maintenance-arrowTop").click(function() {
        $(this)
          .parents(".gg-build-simple")
          .hide();
        $(this)
          .parents(".gg-build-simple")
          .siblings()
          .show();
        $(this)
          .parents(".gg-build-monitor")
          .css("top", "5px");
      });
      //合上
      $(".gg-build-head .maintenance-arrowBottom").click(function() {
        $(this)
          .parents(".gg-build-head")
          .hide();
        $(this)
          .parents(".gg-build-head")
          .siblings(".gg-build-body")
          .hide();
        $(this)
          .parents(".gg-build-head")
          .siblings(".gg-build-simple")
          .show();
        $(this)
          .parents(".gg-build-monitor")
          .css("top", "139px");
      });
      //置顶
      $(".gg-build-monitor").click(function() {
        $(".gg-build-monitor").css("z-index", "0");
        $(this).css("z-index", "10");
      });
    },
    //火警列表
    fireClick() {
      $(".fire-alarm-outside").toggle();
    },
    //地图的点击事件
    mapClick() {
      let _this = this;
      this.g2map.on("click", function(
        button,
        shift,
        screenX,
        screenY,
        mapX,
        mapY,
        handle
      ) {
        var ele = _this.elementLayer.hitTest(screenX, screenY);
        if (ele) {
          _this.videoBool = false; //移除播放视频
          if (ele.element.type == "video") {
            //播放视频
            _this.playerUrl = ele.element.tag.videoPath;
            _this.videoBool = true;
          } else {
            //跳转页面
            _this.openFloorPage(ele.element.tag.buildId);
          }
        }
      });
    },
    //打开楼栋楼层信息页面
    openFloorPage(buildId,floorId,deviceId) {
      this.region = buildId;
      this.currentFloor = floorId;
      this.currentDevice = deviceId;
      this.pageSwitchBool = false;
    },
    //关闭视频
    closeVideo() {
      this.videoBool = false;
      this.playerUrl = "";
    },
    //监听鼠标划入事件
    mapMousemove() {
      let _this = this;
      this.g2map.on("mousemove", function(
        button,
        shift,
        screenX,
        screenY,
        mapX,
        mapY,
        handle
      ) {
        document.getElementById("g2map").style.cursor = "";
        var ele = _this.elementLayer.hitTest(screenX, screenY);
        if (ele) {
          document.getElementById("g2map").style.cursor = "pointer";
        }
      });
    }
  },
  mounted() {
    this.orgId = api.getGlobalVal("maintenance_userObj").orgCode;
    const _this = this;
    this.$nextTick(function() {
      _this.initPage();
    })
  }
};
</script>
<style lang="scss" scoped>
.real-time-div {
  height: 100%;
  width: 100%;
}
#g2map{
	height:100%;
}
/deep/.gg-build-monitor {
  width: 185px;
  background: #4356c5;
  padding-top: 5px;
  padding-bottom: 5px;
  position: relative;
  border-radius: 4px;
  .gg-build-head {
    height: 35px;
    padding-left: 6px;
    color: #fff;
    font-size: 0.14rem;
    .build-head-name {
      display: inline-block;
      width: 150px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      text-align: center;
    }
    .maintenance-arrowBottom {
      position: relative;
      top: -7px;
      cursor: pointer;
    }
  }
  .gg-build-body {
    margin-top: 0.05rem;
    width: 174px;
    height: 128px;
    background: #fff;
    border-radius: 4px;
    margin: 0 auto;
    padding: 0;
    .total_stateNum {
      height: 30px;
      line-height: 30px;
      border-bottom: 1px solid #e6e6e6;
      .build_state_title {
        float: left;
        margin-left: 18px;
      }
      .build_state_num {
        float: right;
        margin-right: 18px;
      }
    }
    .build_stateNum {
      position: relative;
      height: 24px;
      line-height: 24px;
      .build_state_title {
        float: left;
        margin-left: 18px;
      }
      .build_state_num {
        float: right;
        margin-right: 18px;
      }
    }
  }
  .gg-build-simple {
    background: #fff;
    width: 174px;
    height: 30px;
    font-size: 14px;
    line-height: 30px;
    margin: 0 auto;
    padding: 0;
    .simple-state-trouble,
    .simple-state-warn,
    .simple-state-alarm {
      width: 20px;
      height: 30px;
      float: left;
    }
    .simple-state-alarm {
      background: url("~@/static/img/RealTimeMonitoring/simple-logo-alarm.png")
        no-repeat center;
    }
    .simple-state-warn {
      background: url("~@/static/img/RealTimeMonitoring/simple-logo-warn.png")
        no-repeat center;
    }
    .simple-state-trouble {
      background: url("~@/static/img/RealTimeMonitoring/simple-logo-hidden.png")
        no-repeat center;
    }
    .simple-head-name {
      display: inline-block;
      width: 136px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      text-align: center;
      color: #5163c9;
    }
    .maintenance-arrowTop {
      margin-top: 8px;
      color: #5163c9;
      cursor: pointer;
      display: inline-block;
      width: 14px;
      float: right;
      margin-right: 4px;
    }
  }
}
.btn-close {
  cursor: pointer;
  z-index: 20000;
  display: block;
  position: absolute;
  right: 15px;
  top: 15px;
  width: 25px;
  height: 25px;
  color: #fff;
  font-size: 0.27rem;
}
.gg-fire-content {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 20;
  .gg-fire-icon {
    position: relative;
    width: 65px;
    height: 65px;
    text-align: center;
    border-radius: 5px;
    z-index: 20;
    cursor: pointer;
    background: url("~@/static/img/RealTimeMonitoring/fire-logo.png") no-repeat
      center;
  }
  .gg-fire-icon_fire {
    background-color: #ff0000;
    border: 5px solid rgba(255, 87, 87, 0.5);
  }

  .gg-fire-icon_default {
    background-color: #b3b3b3;
    border: 5px solid rgba(179, 179, 179, 0.5);
  }
  .fire-alarm-outside {
    display: none;
    position: absolute;
    bottom: 80px;
    right: 0;
    background-color: #fff;
    border-radius: 5px;
    padding: 0 10px;
    transition: all ease-in-out 0.1s;
    transform-origin: 50% 50%;
    z-index: 10;
    border: 2px solid #bfbfbf;
    .gg-fire-panel {
      // width: 380px;
      max-height: 370px;
      overflow-y: auto;
      background: #fff;
      .gg-text-notice {
        padding-bottom: 5px;
        padding-top: 5px;
        font-size: 14px;
        width: 70px;
      }
      .fire-alarm-outside::before {
        content: "";
        position: absolute;
        left: 92%;
        bottom: -18px;
        display: block;
        width: 0;
        height: 0;
        border: 9px solid transparent;
        margin-left: -9px;
        border-top-color: #fff;
      }
      .gg-fire-dd {
        margin-left: 10px;
        display: inline-block;
        width: 74%;
      }
      .gg-fire-date {
        color: #f00;
        font-size: 12px;
      }
      .gg-fire-title {
        width: 100%;
        color: #000;
        font-size: 16px;
        line-height: 24px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }

      .fire-alarm-time {
        width: 22%;
        float: left;
        text-align: center;
      }
      .gg-fire-dt {
        height: 28px;
        line-height: 28px;
        font-size: 20px;
        color: #f00;
        border: 1px solid #f00;
        border-radius: 20px;
        background: #f0d3d3;
        margin-bottom: 4px;
      }
      .gg-fire-add {
        font-size: 16px;
        margin-top: 4px;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .gg-fire-dl {
        width: 380px;;
        position: relative;
        margin: 0;
        padding-top: 10px;
        padding-bottom: 10px;
        cursor: pointer;
      }
      .gg-fire-bd {
        border-bottom: 1px solid #bfbfbf;
      }
    }
    .fire-none-data {
      width: 200px;
      min-height: 100px;
    }
  }
  .fire-alarm-outside::before {
    content: "";
    position: absolute;
    right: 22px;
    bottom: -22px;
    display: block;
    width: 0;
    height: 0;
    border: 11px solid transparent;
    margin-left: -9px;
    border-top-color: #bfbfbf;
  }
  .fire-alarm-outside::after {
    content: "";
    position: absolute;
    right: 23px;
    bottom: -18px;
    display: block;
    width: 0;
    height: 0;
    border: 10px solid transparent;
    margin-left: -9px;
    border-top-color: #fff;
  }
}
/deep/.gg-build-monitor:before {
  content: "";
  position: absolute;
  left: 50%;
  bottom: -0.2rem;
  display: block;
  border: 0.1rem solid transparent;
  margin-left: -0.09rem;
  border-top-color: #4356c5;
}
@media screen and (max-width: 1440px) {
}
</style>
